<?php


namespace app\web\controller;


use app\api\controller\v2\Auth;
use app\common\cachemodel\SystemConfig;
use app\common\cachemodel\ZlBirthdayWish;
use app\common\cachemodel\BirthBoon;
use app\common\lib\exception\ApiException;
use app\common\lib\Jssdk;
use app\common\lib\Util;
use app\common\model\Recode;
use think\Cache;
use think\Controller;
use think\Env;
use think\Exception;

class Birthday extends Controller
{
    public function _initialize()
    {
        parent::_initialize();

        $this->assign('oss', Env::get('host.photo'));
        $this->assign('domain', Env::get('host.domain'));
        $res = Util::androidVersion('2.2.0');
        $this->assign('version', $res);
    }

    /**
     * 星座名
     * @var string[]
     */
    protected $astroEnglish = [
        1 => 'ARIES',
        2 => 'TAURUS',
        3 => 'GEMINI',
        4 => 'CANCER',
        5 => 'LEO',
        6 => 'VIRGO',
        7 => 'LIBRA',
        8 => 'SCORPIO',
        9 => 'SAGITTARIUS',
        10 => 'CAPRICORN',
        11 => 'AQUARIUS',
        12 => 'PISCES',
    ];

    /**
     * 星座颜色
     * @var string[]
     */
    protected $astroColor = [
        1 => '#FFFFFF',
        2 => '#FFFFFF',
        3 => '#FFFFFF',
        4 => '#FFFFFF',
        5 => '#FFFFFF',
        6 => '#FFFFFF',
        7 => '#FFFFFF',
        8 => '#FFFFFF',
        9 => '#FFFFFF',
        10 => '#FFFFFF',
        11 => '#FFFFFF',
        12 => '#FFFFFF',
    ];

    /**
     * 星座图片 生日分享页及其他使用
     * @var string[]
     */
    protected $astroImg = [
        1 => '/web/static/birthday/birthday_icon1.png',
        2 => '/web/static/birthday/birthday_icon2.png',
        3 => '/web/static/birthday/birthday_icon3.png',
        4 => '/web/static/birthday/birthday_icon4.png',
        5 => '/web/static/birthday/birthday_icon5.png',
        6 => '/web/static/birthday/birthday_icon6.png',
        7 => '/web/static/birthday/birthday_icon7.png',
        8 => '/web/static/birthday/birthday_icon8.png',
        9 => '/web/static/birthday/birthday_icon9.png',
        10 => '/web/static/birthday/birthday_icon10.png',
        11 => '/web/static/birthday/birthday_icon11.png',
        12 => '/web/static/birthday/birthday_icon12.png',
    ];

    /**
     * 星座图片 仅权益页使用
     * @var string[]
     */
    protected $astroImgBoon = [
        1 => '/web/static/birthday/birthday_boon_icon1.png',
        2 => '/web/static/birthday/birthday_boon_icon2.png',
        3 => '/web/static/birthday/birthday_boon_icon3.png',
        4 => '/web/static/birthday/birthday_boon_icon4.png',
        5 => '/web/static/birthday/birthday_boon_icon5.png',
        6 => '/web/static/birthday/birthday_boon_icon6.png',
        7 => '/web/static/birthday/birthday_boon_icon7.png',
        8 => '/web/static/birthday/birthday_boon_icon8.png',
        9 => '/web/static/birthday/birthday_boon_icon9.png',
        10 => '/web/static/birthday/birthday_boon_icon10.png',
        11 => '/web/static/birthday/birthday_boon_icon11.png',
        12 => '/web/static/birthday/birthday_boon_icon12.png',
    ];

    /**
     * 生日权益
     */
    public function boon()
    {
        $isTest = false;//调试开关
        $headers = $this->request->header();
        $timezone = $headers['timezone'] ?? 8;

        if (!$isTest)
        {
            //校验token
            try
            {
                $auth = new Auth();
                $auth->checkRequestAuth();
                $rid = $auth->user['rid'];
                $uid = (int)$auth->user['id'];
            }
            catch (Exception $e)
            {
                throw new ApiException('生日权益，错误：权限认证失败,请稍后重试！');
            }
        } else
        {
            $rid = 4921268;
            $uid = 12345465;
        }

        if (!$rid)
        {
            throw new ApiException('档案不存在', 200, config('code.error'));
        }

        $recodeInfo = (new Recode())->getRecode(['id' => $rid]);

        $utilModel = new Util();

        $sun = mb_substr($utilModel->recodeAstro($recodeInfo['sun']), 0, 2);
        $moon = mb_substr($utilModel->recodeAstro($recodeInfo['moon']), 0, 2);
        $asc = mb_substr($utilModel->recodeAstro($recodeInfo['asc']), 0, 2);

        $astroDataTxt = sprintf("—  日%s月%s升%s  —", $sun, $moon, $asc);
        $inSign = explode('-', $recodeInfo['sun'])[0];

        unset($headers['cookie'], $headers['time'], $headers['content-type'], $headers['content-length']);
        $headersStr = json_encode($headers);

        $birth_coupon = (new BirthBoon())->getBirthBoon();
        // 获取系统配置
        $config = (new SystemConfig())->getSystemConfig(['birthday_boon_desc1', 'birthday_boon_desc2']);
        $intro = array_values($config);

        // 领取生日权益
        $birthdayBoonModel = new BirthBoon();
        $giveResult = $birthdayBoonModel->birthdayCouponGive($uid);
        $date = gmdateModify('Ymd', time(), 8, $timezone);

        $giveflagCacheKey = 'birthday:give:flag:' . $date . ':' . $uid; // 生日权益领取标志  今天领取到权益标志为1；不弹领取失败错误提示

        if ($giveResult)
        {
            Cache::set($giveflagCacheKey, 1, 86400);
            $birthdayBoonGiveRes = [
                'is_show_msg' => 1,
                'msg' => '权益领取成功！'
            ];// 弹成功提示
        } else
        {
            $flag = Cache::get($giveflagCacheKey);
            if ($flag)
            {
                $birthdayBoonGiveRes = [
                    'is_show_msg' => 0,
                    'msg' => '权益领取成功！'
                ]; // 不弹成功提示
            } else
            {
                $birthdayBoonGiveRes = [
                    'is_show_msg' => 1,
                    'msg' => $birthdayBoonModel->errorMsg
                ];// 弹失败提示
            }
        }

        return $this->fetch('boon', [
            'avatar' => $recodeInfo['avatar'] ?: '/avatar_default_2.png',
            'nickname' => $recodeInfo['name'],
            'birth_text' => '- ' . $recodeInfo['year'] . '.' . $recodeInfo['month'] . '.' . $recodeInfo['day'] . ' -',
            'headers' => $headersStr,
            'astro_data_text' => $astroDataTxt,
            'astro_desc' => $this->astroEnglish[$inSign] ?? '',
            'app_type' => $headers['app-type'] ?? '',
            'astro_img' => $this->astroImgBoon[$inSign] ?? '',
            'coupon' => $birth_coupon,
            'boon_give_res' => json_encode($birthdayBoonGiveRes)
        ]);
    }

    /**
     * 发送生日祝福
     */
    public function sendWish()
    {
        $rid = input('rid/d', 0);
        $headers = $this->request->header();
        $isTest = false;

        if (!$isTest)
        {
            if (!$rid)
            {
                throw new ApiException('请求异常；档案缺失', 200, config('code.error'));
            }
            //校验token
            try
            {
                $auth = new Auth();
                $auth->checkRequestAuth();
                $uid = $auth->user['id'];
            }
            catch (Exception $e)
            {
                throw new ApiException('发送生日祝福，错误：权限认证失败,请稍后重试！');
            }
        } else
        {
            $rid = 4921268;
            $uid = 12345465;
        }

        $recodeInfo = (new Recode())->getRecode(['id' => $rid]);

        if (!$recodeInfo || $recodeInfo['uid'] != $uid)
        {
            throw new ApiException('档案不存在', 200, config('code.error'));
        }

        $utilModel = new Util();

        $sun = mb_substr($utilModel->recodeAstro($recodeInfo['sun']), 0, 2);
        $moon = mb_substr($utilModel->recodeAstro($recodeInfo['moon']), 0, 2);
        $asc = mb_substr($utilModel->recodeAstro($recodeInfo['asc']), 0, 2);

        $astroDataTxt = sprintf("— 日 %s 月 %s 升 %s  —", $sun, $moon, $asc);
        $inSign = explode('-', $recodeInfo['sun'])[0];

        unset($headers['cookie'], $headers['time'], $headers['content-type'], $headers['content-length']);
        $headersStr = json_encode($headers);

        return $this->fetch('', [
            'avatar' => $recodeInfo['avatar'] ?: '/avatar_default_2.png',
            'nickname' => $recodeInfo['name'],
            'headers' => $headersStr,
            'astro_data_text' => $astroDataTxt,
            'astro_desc' => $this->astroEnglish[$inSign] ?? '',
            'app_type' => $headers['app-type'] ?? '',
            'astro_img' => $this->astroImg[$inSign] ?? '',
        ]);
    }

    /**
     * 查看祝福详情
     */
    public function getWishInfo()
    {
        $id = input('id/d', 0);

        if (!$id)
        {
            throw new ApiException('请求异常；祝福ID缺失', 200, config('code.error'));
        }

        $data = (new ZlBirthdayWish())->getWishInfo($id, ['self_rid', 'send_rid', 'wish']);

        if (!$data)
        {
            throw new ApiException('请求异常；祝福ID不存在', 200, config('code.error'));
        }
        // 发送祝福用户的档案
        $sendRecodeInfo = (new Recode())->getRecode(['id' => $data['self_rid']]);
        if (!$sendRecodeInfo)
        {
            throw new ApiException('祝福异常；祝福ID：' . $id . '，档案不存在;ID:' . $data['send_rid'], 200, config('code.error'));
        }
        // 收到祝福的档案ID
        $recodeInfo = (new Recode())->getRecode(['id' => $data['send_rid']]);
        if (!$recodeInfo)
        {
            throw new ApiException('祝福异常；祝福ID：' . $id . '，档案不存在;ID:' . $data['send_rid'], 200, config('code.error'));
        }

        $utilModel = new Util();
        $sun = mb_substr($utilModel->recodeAstro($recodeInfo['sun']), 0, 2);
        $moon = mb_substr($utilModel->recodeAstro($recodeInfo['moon']), 0, 2);
        $asc = mb_substr($utilModel->recodeAstro($recodeInfo['asc']), 0, 2);

        $astroDataTxt = sprintf("— 日%s月%s升%s  —", $sun, $moon, $asc);
        $inSign = explode('-', $recodeInfo['sun'])[0];

        $signPackage = (new Jssdk())->getSignPackage();

        return $this->fetch('', [
            'signPackage' => $signPackage,
            'send_user' => [
                'avatar' => $sendRecodeInfo['avatar'] ?: '/avatar_default_2.png',
                'nickname' => $sendRecodeInfo['name'],
            ],
            'avatar' => $recodeInfo['avatar'] ?: '/avatar_default_2.png',
            'nickname' => $recodeInfo['name'],
            'astro_data_text' => $astroDataTxt,
            'astro_desc' => $this->astroEnglish[$inSign] ?? '',
            'wish_content' => htmlspecialchars($data['wish']),
            'astro_img' => $this->astroImg[$inSign] ?? '',
            'astro_bg_color' => $this->astroColor[$inSign]
        ]);
    }

    /**
     *
     */
    public function smsTemplate()
    {
        $headers = $this->request->header();
        unset($headers['cookie'], $headers['time'], $headers['content-type'], $headers['content-length']);
        $headersStr = json_encode($headers);
        $birth_coupon = (new BirthBoon())->getBirthBoon();
        return $this->fetch('sms_template', [
            'headers' => $headersStr,
            'app_type' => $headers['app-type'] ?? '',
            'coupon' => $birth_coupon,
        ]);
    }
}
